<template>
  <div class="ADDORDER_PAFE">
    <el-form :model="formData" label-position="top" class="demo-form-inline">
      <el-form-item v-if="orderType == 1" label="房间号">
        <el-input v-model="formData.roomNumber" placeholder="请输入房间号" clearable />
      </el-form-item>

      <el-form-item v-else label="会议室名称">
        <el-select v-model="formData.roomNumber" placeholder="请输入会议室名称" clearable>
          <el-option v-for="(item, index) in roomList" :key="index" :label="item" :value="item" />
        </el-select>
      </el-form-item>

      <el-form-item label="需求名称">
        <el-input v-model="formData.orderTitle" placeholder="请输入需求名称" clearable />
      </el-form-item>

      <el-form-item label="手机号">
        <el-input v-model="formData.iphoneNumber" placeholder="请输入手机号" clearable />
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="formData.orderDetail"
          type="textarea"
          :rows="4"
          placeholder="请输入描述"
          clearable
        />
      </el-form-item>
      <el-form-item label="图片">
        <!-- 显示已上传图片（显示服务器返回的在线地址） -->
        <div v-if="uploadedImages.length" class="preview-list">
          <div v-for="(image, index) in uploadedImages" :key="index" class="preview-item">
            <img :src="image" @click="handlePreview(image)" />
            <el-icon class="delete-icon" @click="handleRemove(index)">
              <Close />
            </el-icon>
          </div>
        </div>

        <!-- 上传按钮 -->
        <div
          class="mobile-upload-btn"
          @click="showMobileAction"
          :disabled="uploading"
          :style="{ opacity: uploading ? 0.7 : 1 }"
        >
          <el-icon><Plus /></el-icon>
          <span>{{ uploading ? "上传中..." : "上传图片" }}</span>
          <span class="upload-count" v-if="uploadedImages.length > 0">
            ({{ uploadedImages.length }}/5)
          </span>
        </div>
        <div class="upload-tips" v-if="uploading">上传进度: {{ uploadProgress }}%</div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="submitting">
          {{ submitting ? "提交中..." : "提交" }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewImage" style="max-width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup name="addOrder">
import { reactive, ref, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { Plus, Close } from "@element-plus/icons-vue"
import { selectRoomName } from "@/api/login.js"
import { useRoute } from "vue-router"

const formData = reactive({
  roomNumber: "",
  orderTitle: "",
  iphoneNumber: "",
  orderDetail: "",
})

const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/system/qr/uploadPic"
const roomList = ref([])
const uploadedImages = ref([])
const previewVisible = ref(false)
const previewImage = ref("")
const uploading = ref(false)
const orderType = ref(1)
const slaId = ref(0)
const uploadProgress = ref(0)
const submitting = ref(false)

onMounted(() => {
  const route = useRoute()
  orderType.value = route.query.type
  document.title = `${route.query.title}(${route.query.type == 1 ? "客房" : "会议室"})`
  slaId.value = route.query.slaId

  if (orderType.value == 2) {
    init()
  }
})

const init = async () => {
  const { data: res } = await selectRoomName(slaId.value)
  roomList.value = res
}

const showMobileAction = async () => {
  if (uploading.value) return

  if (uploadedImages.value.length >= 5) {
    ElMessage.warning("最多只能上传5张图片")
    return
  }

  try {
    await ElMessageBox({
      title: "上传图片",
      message: "请选择图片来源",
      showCancelButton: true,
      confirmButtonText: "拍照",
      cancelButtonText: "从相册选择",
    })
    createInput("camera")
  } catch {
    createInput("album")
  }
}

const createInput = (type) => {
  const input = document.createElement("input")
  input.type = "file"
  input.accept = "image/*"

  if (type === "camera") {
    input.capture = "environment"
  }

  // 计算还能上传多少张图片
  const remaining = 5 - uploadedImages.value.length
  input.multiple = true
  input.onchange = async (e) => {
    if (e.target.files && e.target.files.length > 0) {
      uploading.value = true
      uploadProgress.value = 0

      try {
        const files = Array.from(e.target.files).slice(0, remaining)
        const totalFiles = files.length

        for (let i = 0; i < files.length; i++) {
          const file = files[i]
          try {
            const imageUrl = await uploadFile(file, (progress) => {
              // 计算总体进度
              uploadProgress.value = Math.round((i * 100 + progress) / totalFiles)
            })

            uploadedImages.value.push(imageUrl)
            ElMessage.success(`图片 ${i + 1}/${files.length} 上传成功`)
          } catch (error) {
            ElMessage.error(`图片 ${file.name} 上传失败: ${error.message}`)
          }
        }
      } catch (error) {
        ElMessage.error(`上传出错: ${error.message}`)
      } finally {
        uploading.value = false
        uploadProgress.value = 0
      }
    }
  }
  input.click()
}

// 上传文件到服务器并返回图片URL
const uploadFile = (file, onProgress) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    const formData = new FormData()
    formData.append("file", file) // 根据后端接口可能需要调整字段名

    xhr.upload.addEventListener("progress", (e) => {
      if (e.lengthComputable) {
        const percent = Math.round((e.loaded / e.total) * 100)
        onProgress && onProgress(percent)
      }
    })

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText)
            if (response.code === 200 && response.imgUrl) {
              resolve(response.imgUrl)
            } else {
              reject(new Error(response.msg || "上传失败"))
            }
          } catch (e) {
            reject(new Error("解析响应失败"))
          }
        } else {
          reject(new Error(`上传失败: ${xhr.statusText}`))
        }
      }
    }

    xhr.onerror = () => {
      reject(new Error("网络错误"))
    }

    xhr.open("POST", uploadUrl, true)
    // 如果需要token等认证信息
    // xhr.setRequestHeader("Authorization", `Bearer ${localStorage.getItem('token')}`)
    xhr.send(formData)
  })
}

const handlePreview = (url) => {
  previewImage.value = url
  previewVisible.value = true
}

const handleRemove = (index) => {
  uploadedImages.value.splice(index, 1)
}

const onSubmit = async () => {
  if (submitting.value) return
  submitting.value = true

  try {
    // 表单验证
    if (!formData.roomNumber) {
      ElMessage.warning("请输入房间号")
      return
    }

    if (!formData.iphoneNumber) {
      ElMessage.warning("请输入手机号")
      return
    }

    // 构造提交数据
    const submitData = {
      roomNumber: formData.roomNumber,
      orderTitle: formData.orderTitle,
      iphoneNumber: formData.iphoneNumber,
      orderDetail: formData.orderDetail,
      slaId: slaId.value,
      initUrl: ''
    }

    uploadedImages.value.forEach((item, index) => {
        initUrl+= `${item}${index == uploadedImages.value.length - 1 ? '' : ';'}`
    })


    // 发送请求到提交接口
    const response = await fetch(import.meta.env.VITE_APP_BASE_API + "/system/qr/createWorkOrder", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(submitData),
    })

    if (!response.ok) {
      throw new Error(`HTTP错误! 状态码: ${response.status}`)
    }

    const result = await response.json()

    // 根据你的接口返回格式判断
    if (result.code === 200) {
      ElMessage.success(result.msg || "提交成功")
      console.log("提交结果:", result)
      resetForm()
    } else {
      throw new Error(result.msg || "提交失败")
    }
  } catch (error) {
    console.error("提交出错:", error)
    ElMessage.error(error.message || "提交失败，请重试")
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formData.roomNumber = ""
  formData.orderTitle = ""
  formData.iphoneNumber = ""
  formData.orderDetail = ""
  uploadedImages.value = []
}
</script>

<style lang="scss" scoped>
.ADDORDER_PAFE {
  width: 100vw;
  min-height: calc(100vh - 40px);
  padding: 40px 20px;

  :deep(.el-input__wrapper) {
    padding: 10px;
  }

  :deep(.el-select__wrapper) {
    padding: 18px 12px;
  }

  .mobile-upload-btn {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    &:disabled {
      cursor: not-allowed;
    }

    .el-icon {
      font-size: 24px;
      margin-bottom: 8px;
      color: #8c939d;
    }

    .upload-count {
      font-size: 12px;
      color: #666;
    }
  }

  .upload-tips {
    margin-top: 8px;
    font-size: 12px;
    color: #666;
  }

  .preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 10px;

    .preview-item {
      position: relative;
      width: 100px;
      height: 100px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 6px;
        cursor: pointer;
        border: 1px solid #eee;
      }

      .delete-icon {
        position: absolute;
        top: -8px;
        right: -8px;
        background: #f56c6c;
        color: white;
        border-radius: 50%;
        padding: 4px;
        cursor: pointer;
        font-size: 12px;

        &:hover {
          background: #f78989;
        }
      }
    }
  }
}
</style>
